# _*_ coding: utf-8 _*_
# @Time:2024/5/17 17:23
# @Author:10917
# @File:custom_exceptions.py
from rest_framework.views import exception_handler


def extract_error_message(exc):
    """
    自定义解析错误异常msg的方法
    """
    if hasattr(exc, 'detail') and isinstance(exc.detail, dict):
        error_messages = []
        for field, errors in exc.detail.items():
            for error in errors:
                if isinstance(error, str):
                    error_messages.append(f"{field} {error}")
                elif hasattr(error, 'code') and hasattr(error, 'message'):
                    error_messages.append(f"{field} {error.message}")
        return error_messages
    return str(exc)


def custom_exception_handler(exc, context):
    """
    定义全局接口异常之后的返回格式结构

    :param exc:
    :param context:
    :return:
    """
    response = exception_handler(exc, context)

    if response is not None:
        customized_response = {
            'status': 0,
            'msg': extract_error_message(exc),
            'data': []
        }
        response.data = customized_response

    return response
